import { computed, reactive, provide, watch } from "vue";
import * as util from "@/plugin/util.js";
import { $api } from "@/plugin/$api/$ajax";
import apiTips from "./tips.js";
export default function setup(props, context) {
  console.log("[setup]", props, context);
  let provider = reactive({ doc: null });
  provider.docBase = () => {
    return {
      name: "新建文档",
      baseURL: "/api",
      version: "1.0",
      desc: "",
      author: "",
      createTime: util.dateFormat(),
      group: { "": "" },
      list: {}
    };
  };
  provider.apiBase = () => {
    return {
      group: "",
      name: "新建接口",
      method: "get",
      param: apiTips.param,
      paramSet: apiTips.paramSet,
      result: apiTips.result,
      resultSet: apiTips.resultSet
    };
  };
  provider.setDoc = (doc) => {
    // console.log(props, context);
    provider.doc = Object.assign(provider.docBase(), doc);
    // doc = reactive(Object.assign(docBase(), doc));
  };
  provider.apiGroups = (doc) => {
    let groups = {};
    let list = provider.doc.list;
    for (const i in list) {
      let item = list[i];
      // item = i;
      let groupName = item.group || "默认分组";
      groups[groupName] = groups[groupName] || [];
      groups[groupName].push(item);
    }
    console.log("groups", groups);
    return list && list.length && groups;
  };
  provider.addApi = (api) => {
    let id = [0, ...Object.values(provider.doc.list || {})].reduce((idMax, i) => {
      return Math.floor(i > 0 && i > idMax ? i : idMax) + 1;
    });
    console.log(id);
    provider.doc.list[id] = Object.assign(provider.apiBase(), { name: "新建接口" + id, id }, api);
    return provider.doc.list[id];
    // provider.doc.list.unshift(Object.assign(provider.apiBase(), api));
  };
  provider.removeApi = (index, num) => {
    delete provider.doc.list[index];
    // provider.doc.list.splice(index, num);
  };
  provide("apiDoc", provider);
  return provider;
}
